<script setup>

</script>

<template>
  <div class="app-container">
    <!-- 积分商品信息 -->
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>积分商品信息</span>
        </div>
      </template>
      
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <!-- 只读信息 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品名称">
              <el-input v-model="form.productName" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="SKU编码">
              <el-input v-model="form.productSn" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="店铺名称">
              <el-input v-model="form.storeName" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品价格">
              <el-input v-model="form.originalPrice" readonly>
                <template #prepend>¥</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="库存">
              <el-input v-model="form.stock" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结算价格" >
              <el-input v-model="form.price" readonly>
                <template #prepend>¥</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 可编辑字段 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="分类" prop="categoryId" required>
              <el-select v-model="form.categoryId" placeholder="请选择分类" style="width: 100%">
                <el-option
                  v-for="item in categoryOptions"
                  :key="item.id"
                  :label="item.categoryName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="活动库存" prop="activityRemainingStock" required>
              <el-input v-model="form.activityRemainingStock" placeholder="请输入活动库存" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="兑换积分" prop="exchangePoints" required>
              <el-input v-model="form.exchangePoints" placeholder="请输入兑换积分" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="活动时间" prop="activityTime" required>
              <el-date-picker
                v-model="form.activityTime"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 操作按钮 -->
        <el-form-item>
          <el-button @click="goBack">返回</el-button>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup name="UpdateProduct">
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { getProducts, updateProducts } from "@/api/promotion/products"
import { listCategories } from "@/api/promotion/categories"

const { proxy } = getCurrentInstance()
const router = useRouter()
const route = useRoute()

// 响应式数据
const formRef = ref()
const categoryOptions = ref([])

// 表单数据
const form = reactive({
  id: null,
  productName: '',
  productSn: '',
  storeName: '',
  price: '',
  stock: '',
  originalPrice: '',
  categoryId: null,
  activityRemainingStock: '',
  exchangePoints: '',
  activityTime: '' // Changed from activityStartTime and activityEndTime
})

// 表单验证规则
const rules = reactive({
  originalPrice: [
    { required: true, message: '请输入结算价格', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  activityRemainingStock: [
    { required: true, message: '请输入活动库存', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value && parseInt(value) > parseInt(form.stock)) {
          callback(new Error('活动库存不能大于库存数'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ],
  exchangePoints: [
    { required: true, message: '请输入兑换积分', trigger: 'blur' }
  ],
  activityTime: [ // Updated rule for activityTime
    { required: true, message: '请选择活动时间', trigger: 'change' }
  ]
})

// 页面加载时获取数据
onMounted(() => {
  const id = route.query.id
  const productData = route.query.productData
  
  if (id) {
    // 如果有传递的商品数据，直接使用
    if (productData) {
      const data = JSON.parse(productData)
      Object.assign(form, data)
      // 将开始时间和结束时间合并为时间范围
      if (data.activityStartTime && data.activityEndTime) {
        form.activityTime = [data.activityStartTime, data.activityEndTime]
      }
    } else {
      // 否则重新获取
      getProductData(id)
    }
  }
  
  // 获取分类选项
  getCategoryOptions()
})

// 获取商品数据
function getProductData(id) {
  getProducts(id).then(response => {
    Object.assign(form, response.data)
    // 将开始时间和结束时间合并为时间范围
    if (response.data.activityStartTime && response.data.activityEndTime) {
      form.activityTime = [response.data.activityStartTime, response.data.activityEndTime]
    }
  })
}

// 获取分类选项
function getCategoryOptions() {
  listCategories({}).then(response => {
    categoryOptions.value = response.rows
  })
}

// 返回上一页
function goBack() {
  router.go(-1)
}

// 提交表单
function handleSubmit() {
  formRef.value.validate(valid => {
    if (valid) {
      // 将时间范围拆分为开始时间和结束时间
      const submitData = { ...form }
      if (form.activityTime && form.activityTime.length === 2) {
        submitData.activityStartTime = form.activityTime[0]
        submitData.activityEndTime = form.activityTime[1]
        delete submitData.activityTime
      }
      
      updateProducts(submitData).then(response => {
        proxy.$modal.msgSuccess("修改成功")
        // 跳转到列表页面并传递刷新参数
        router.push({
          path: '/promotion/products',
          query: { refresh: 'true' }
        })
      }).catch(() => {
        proxy.$modal.msgError("修改失败")
      })
    }
  })
}
</script>

<style scoped lang="scss">
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.box-card {
  margin-bottom: 20px;
}
</style>